let baseUrl = "https://www.ihed.org.cn";
// var baseUrl = "http://192.168.1.201:8080/";


function checkLogin(){
	var memberInfo = getLocalStorage("memberInfo");
	if(!memberInfo){
		return false;
	}
	return true;
}

function toLogin(){
	var localurl = window.location.href;
	localurl = encodeURIComponent(localurl);
	if(is_weixn()){
		var ua= window.navigator.userAgent.toLowerCase();
		if( (ua.match(/MicroMessenger/i) == 'micromessenger') && (ua.match(/wxwork/i) == 'wxwork') ){
			//企业微信打开
			window.location.href= baseUrl+'/pages/login/login?redirect='+localurl;
		}else{
			window.location.href= baseUrl+'/pages/login/wxLogin?redirect='+localurl;
		}
	}else {
		window.location.href= baseUrl+'/pages/login/login?redirect='+localurl;
	}
}

//判断是否是微信打开
function is_weixn(){
	var ua = navigator.userAgent.toLowerCase();
	if(ua.match(/MicroMessenger/i)=="micromessenger") {
		return true;
	} else {
		return false;
	}
}

function clearToken(){
	localStorage.removeItem("mem_token");
	localStorage.removeItem("memMobile");
}

/**
 * 微信支付
 * @param resdata
 * @param orderInfo
 */
function chooseWXPay(resdata, orderInfo) {
	let url = window.location.href
	let that = this;
	try {
		const res = request.get('/mevosMmember/member/rlogin/share', true, {
			redirectUrl: url
		}).then(res => {
			console.log(res);
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: res.data.appId, // 必填，公众号的唯一标识
				timestamp: res.data.timestamp, // 必填，生成签名的时间戳
				nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
				signature: res.data.signature, // 必填，签名
				jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage',
					'updateAppMessageShareData', 'updateTimelineShareData',
					'hideAllNonBaseMenuItem', 'showMenuItems', 'closeWindow', 'chooseWXPay'
				] // 必填，需要使用的JS接口列表
			})
			wx.chooseWXPay({
				timestamp: resdata.data
					.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: resdata.data.nonceStr, // 支付签名随机串，不长于 32 位
				package: resdata.data.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: resdata.data.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
				paySign: resdata.data.paySign, // 支付签名
				success: function(resv) {
					Toast("支付成功",2000);
					// 支付成功后的回调函数
				}
			});
		})
		// 保存数据
	} catch (err) {
		Toast(err,2000);
	}
}


/**
 * 获取请求参数代码
 * @param name
 * @returns {string|string}
 */
function getParam(name) {
	const paramArray = location.search.substring(1);
	const paramName = "(^|&)" + name + "=([^&]*)(&|$)"
	const paramReg = new RegExp(paramName, "i");
	return paramArray.match(paramReg) != null && paramArray.match(paramReg).length > 2 ? paramArray.match(
		paramReg)[2] : "";
}

/**
 * toast弹框代码
 * @param msg
 * @param duration
 * @constructor
 */
function Toast(msg, duration) {
	duration = isNaN(duration) ? 3000 : duration;
	var m = document.createElement("div");
	m.innerHTML = msg;
	m.style.cssText =
		"position: fixed;top: 50%;left: 50%;padding:5rem 10px;z-index:100000000000000000000000000;padding:20rem;min-width:192rem;max-width: 70%;max-height: 70%;overflow: auto; color: white;word-break: break-all;text-align: center;background-color: rgba(0, 0, 0, 0.7);border-radius: 8rem;transform: translate(-50%, -50%);pointer-events: all;font-size: 25rem;box-sizing: border-box;";
	document.body.appendChild(m);
	setTimeout(function() {
		var d = 0.5;
		m.style.transition = "transform " + d + "s ease-in, opacity " + d + "s ease-in";
		m.style.webkitTransition = "-webkit-transform " + d + "s ease-in, opacity " + d + "s ease-in";
		m.style.opacity = "0";
		setTimeout(function() {
			document.body.removeChild(m);
		}, d * 1000);
	}, duration);
}

/**
 * rem跟px的换算关系
 * designWidth:设计图的宽度 手机大部分情况使用750px为默认宽度
 */
(function (designWidth) {
	/**
	 * 根据窗口大小动态调整根节点font-size大小,动态调整rem跟px的换算关系
	 */
	function reloadRem() {
		//获取窗口宽度
		var width = document.documentElement.getBoundingClientRect().width;
		console.log(width)
		//计算font-szie
		var fontSize = width / designWidth;
		document.documentElement.style.fontSize = fontSize + "px";
	};
	reloadRem();
	window.addEventListener("resize", function () {
		reloadRem()
	}, false);
})(750);


function showErrorMsg(that, msg) {
	that.alertMsg=msg;
	setTimeout(function (){
		that.alertMsg = '';
	},1000)
}
//全局公共请求方法
var requestAjax = {
	get: (url, async, data, method = "get") => {
		return new Promise((resolve, reject) => {
			if (async =="" || async ==null || typeof async =="undefined") {
				async = true;
			}
			$.ajax({
				url: baseUrl + url,
				type: method,
				async: async,
				dataType: "json",
				headers: {
					contentType: "application/x-www-form-urlencoded",
				},
				data: data,
				success: function(res) {
					if (res.code == 200) {
						resolve(res);
					} else if (res.code == 10008) {
						toLogin();
					} else {
						resolve(res);
					}
				},
				error: function(err) {
					if (err.statusCode == 1) {
						//提示用户请求超时，请稍后再试
					}
					resolve(err);
				},
			});
		}).catch(error => {
			console.log('报错的内容:', error)
		});
	},
	post: (url, async, data, header) => {
		return new Promise((resolve, reject) => {
			// 加载中动画开启
			//设置默认异步请求
			if (async =="" || async ==null || typeof async =="undefined") {
				async = true;
			}
			$.ajax({
				url: baseUrl + url,
				type: "post",
				async: async,
				dataType: "json",
				headers: {
					contentType: header || 'application/x-www-form-urlencoded',
				},
				contentType: header || 'application/x-www-form-urlencoded',
				data: data,
				success: function(res) {
					// 加载中动画关闭
					if (res.code == 200) {
						resolve(res);
					} else if (res.code == 10008) {
						toLogin();
					} else {
						resolve(res);
					}
				},
				error: function(err) {
					if (err.statusCode == 1) {
						//请求超时，请稍后再试
					}
					reject(err);
				},
			});
		})
	},
	put: (url, async, data, method = "put") => {
		return new Promise((resolve, reject) => {
			// 加载中动画开启
			//设置默认异步请求
			if (async =="" || async ==null || typeof async =="undefined") {
				async = true;
			}
			$.ajax({
				url: baseUrl + url,
				type: method,
				async: async,
				dataType: "json",
				data: data,
				headers: {
					Token: localStorage.getItem("token"), //自定义请求头
					"Content-Type": "application/json;charset=utf8",
				},
				success: function(res) {
					// 加载中动画关闭
					// loading && loading.close();
					if (res.code == 200) {
						resolve(res);
					} else if (res.code == 10008) {
						toLogin();
					} else {
						resolve(res);
					}
				},
				error: function(err) {
					if (err.statusCode == 1) {
						//  请求超时，请稍后再试
					}
					reject(err);
				},
			});
		}).catch(error => {
			console.log('报错的内容:', error)
		});
	},
	delete: (url, async, data, method = "delete") => {
		return new Promise((resolve, reject) => {
			// 加载中动画开启
			//设置默认异步请求
			if (async =="" || async ==null || typeof async =="undefined") {
				async = true;
			}
			$.ajax({
				url: baseUrl + url,
				type: method,
				async: async,
				dataType: "json",
				data: data,
				headers: {
					Token: localStorage.getItem("token"), //自定义请求头
					"Content-Type": "application/json;charset=utf8",
				},
				success: function(res) {
					if (res.code == 200) {
						resolve(res);
					} else if (res.code == 10008) {
						toLogin();
					} else {
						resolve(res);
					}
				},
				error: function(err) {
					if (err.statusCode == 1) {}
					reject(err);
				},
			});
		}).catch(error => {
			console.log('报错的内容:', error)
		});
	},
}
window.request = requestAjax;


function setLocalStorage(key, data){
	if(data!=null && (typeof data === 'object')){//数组or对象
		data = JSON.stringify(data);
	}
	localStorage.setItem(key, data);
}

function getLocalStorage(key){
	const val = localStorage.getItem(key);
	if(val===null || val==='null'){
		return null;
	}else if(val==='undefined'){
		return undefined;
	}else{
		try{
			return JSON.parse(val);//解析成功说明是JSON
		}catch (e) { //解析失败按原值返回
			return val;
		}
	}
}


